package stu.kurs.security;

import java.io.IOException;
import javax.ejb.EJB;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import stu.kurs.exceptions.ServiceException;
import stu.kurs.services.IUserService;
import com.sun.appserv.security.ProgrammaticLogin;

@WebServlet(name = "LoginServlet", urlPatterns = {"/login"})
public class LoginServlet extends HttpServlet {

	private static final long serialVersionUID = 9184140023388298845L;
	@EJB(name="Userservice")
	private IUserService userService;

	@Override
    protected void doGet( HttpServletRequest request, HttpServletResponse response )
            throws ServletException, IOException {
        response.sendError( HttpServletResponse.SC_FORBIDDEN );
    }

    @Override
    protected void doPost( HttpServletRequest request, HttpServletResponse response )
            throws ServletException, IOException {
        ProgrammaticLogin pl = new ProgrammaticLogin();
        try {
        	Boolean rc = pl.login( request.getParameter("email"), request.getParameter("password").toCharArray(), "y_londonRealm", request, response, true );
            if(rc != null && rc.booleanValue()) {
            	try{
            		setUserInfo(request);
            	}
            	catch (ServiceException e){
            		pl.logout();
            		response.sendRedirect("/y_london/pages/authorization.html?fail=true");
            	}
                response.sendRedirect("/y_london/pages/welcome.html");
            }
        } catch( Exception e ) {
        	response.sendRedirect("/y_london/pages/authorization.html?fail=true");
        }  
    }

    @Override
    public String getServletInfo() {
        return "Login servlet";
    }
    
    private void setUserInfo(HttpServletRequest request) throws ServiceException{
    	request.getSession().setAttribute("user_id", userService.findByEmail(request.getParameter("email")).getId());
    }
}
